<?php
    use think\Db;

    /**
     * 用户上级等级升级
     */
    function userMemberUp($uid){
        $pid = Db::name('LcUser')->where('id',$uid)->value('pid');
        userMemberUp2($pid);
    }
    function userMemberUp2($pid,$member = null){
        $parent = Db::name('LcUser')->find($pid);
        if(empty($parent) || $parent['depth']==0){
            return;
        }
        
        //升级
        (function($parent,$member){
            //下一等级
            if($member==null){
                $member = Db::name('LcUserMember')->where("id > {$parent['mid']}")->order("id asc")->find();
            }
            if(empty($member)){
                return;
            }
            //团队业绩
            $money = userTeamRechargeTotal($parent);
            if($money<$member['need_amount']){//需要业绩
                return;
            }
            //下级等级要求 (0级的有效会员为已充值过)
            $where = "lft>{$parent['lft']} and lft<{$parent['rgt']}";
            if($member['need_mid']>0){
                $where .= " and mid>={$member['need_mid']}";
            }else{
                $where .= " and (mid>{$member['need_mid']} || `value`>0)";
            }
            $mcount = Db::name('LcUser')->where($where)->count();
            if($mcount<$member['need_mid_count']){
                return;
            }
    
            //升级
            Db::name('LcUser')->where(['id' => $parent['id']])->update(['mid' => $member['id']]);
    
            //继续升下一等级
            $memberNext = Db::name('LcUserMember')->where("id > {$member['id']} ")->order("id asc")->find();
            if(!empty($memberNext)){
                userMemberUp2($parent['id'],$memberNext);
            }
        })($parent,$member);
        
        //继续升级上级
        if($member==null && $parent['pid']>0){
            userMemberUp2($parent['pid']);
        }
    }

    //团队业绩
    function userTeamRechargeTotal($user){
        $money = Db::name('LcUser')->where("lft>{$user['lft']} and lft<{$user['rgt']}")->sum('value');
        return $money;
    }

    /**
     * list转成以k为键的数组
     */
    function keyList($list,$k = 'id'){
        $result = [];
        foreach($list as $value){
            $result[$value[$k]] = $value;
        }
        return $result;
    }
?>